"""
Hibernate：更换数据库时，只需更改方言（Dialect）和数据库驱动（Driver），即可实现对不同数据库的切换。
"""
from abc import ABC, abstractmethod


# 抽象产品
class DatabaseConnect(ABC):
    def __init__(self, dialect, driver):
        self.dialect = dialect
        self.driver = driver

    @abstractmethod
    def connect(self):
        pass


# 具体产品
class MysqlConnect(DatabaseConnect):
    def __init__(self, dialect, driver):
        super().__init__(dialect, driver)

    def connect(self):
        print(f'{self.dialect} 通过 {self.driver} 连接...')


class OracleConnect(DatabaseConnect):
    def __init__(self, dialect, driver):
        super().__init__(dialect, driver)

    def connect(self):
        print(f'{self.dialect} 通过 {self.driver} 连接...')


class RedisConnect(DatabaseConnect):
    def __init__(self, dialect, driver):
        super().__init__(dialect, driver)

    def connect(self):
        print(f'{self.dialect} 通过 {self.driver} 连接...')


class DatabaseConnectFactory:
    def create_connection(self, dialect, driver):
        if dialect is None or driver is None:
            return None

        if dialect.upper() == 'Mysql'.upper() and driver.upper() == 'MysqlDriver'.upper():
            return MysqlConnect(dialect.upper(), driver.upper())
        elif dialect.upper() == 'Oracle'.upper() and driver.upper() == 'OracleDriver'.upper():
            return OracleConnect(dialect.upper(), driver.upp())
        elif dialect.upper() == 'Redis'.upper() and driver.upper() == 'RedisDriver'.upper():
            return RedisConnect(dialect.upper(), driver.upper())

        raise Exception('连接失败, 检查数据库与其驱动是否匹配')


if __name__ == '__main__':
    data_connect_factory = DatabaseConnectFactory()
    mysql_connection = data_connect_factory.create_connection('Mysql', 'mysqlDriver')
    mysql_connection.connect()
